from django.conf import settings
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpResponseRedirect as redirect
from django.contrib.auth import authenticate
from StartGroup.models import Group
from ideas.forms import IdeaForm
from ideas.models import Ideas
import StartGroup.Constants
import connectpeople.Constants
from  django.http import QueryDict
from utils import activity_module, common_query, common_methods
import simplejson
from django.http import HttpResponse
import threading

# render form for Idea
def ideaFormView(request, group_web_address):
    group_web_addr = group_web_address
    group_info = getGroupInfo(group_web_addr)              
    
    # Obtain user id
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)
    
    # Idea form initialization
    idea_form = IdeaForm()
    return render_to_response("ideas/ideaForm.html",
                      {'idea_form': idea_form,'group':group_info,
                       'permission':permission},
                      context_instance = RequestContext(request))
    

# Save the form
def ideaView(request, group_web_address):
    
    group_web_addr = group_web_address
    group = getGroupInfo(group_web_addr)
    userid = request.session[connectpeople.Constants.session_userid]
    
    # Save the Announcement    
    if request.method == 'POST':
        
        try:
            # Take the Action String to identif which action to perform
            action = request.POST.__getitem__('action')
        except:
            action = None        
        
        if action == "deleteIdea":
            # Delete Announcement
            idea_id = request.POST.__getitem__('anid')
            Ideas.objects.get(id=idea_id).delete()
            response = simplejson.dumps({'success':'success'})
        else:
            # Save and insert new row in table
            # Idea form initialization
            idea_form = IdeaForm(data=request.POST)            
            if idea_form.is_valid():
                idea = idea_form.save(userid, group)
                
                # Announcement Update Activity save
                activity_module.setActivityNode(idea.title, userid, group_web_addr, connectpeople.Constants.new_idea_action)
                
                # Get email ids of these users
                recipient_list = common_query.getGroupMembersEmailIds(group_web_addr, connectpeople.Constants.new_idea_email_flag_constant)
                # Compose subject for the email
                subj = "New Idea Posted"
                # Send Email alerts. Use threading to speed up things
                new_comment_thread= threading.Thread(target=common_methods.send_email_helper, kwargs={'a_sender':Ideas, 'a_email':recipient_list, 'a_model':idea, 'a_subject':subj, 'a_template':"email/newIdeaEmail.html"})
                new_comment_thread.setDaemon(True)
                new_comment_thread.start()                   
    
    if request.is_ajax():
        return HttpResponse(response,
        content_type="application/javascript")
    
    # get all the group ideas
    ideas = Ideas.objects.filter(group= group_web_addr).order_by('-created_date')    
    
    # Get User object with permissions assigned
    permission = common_query.get_user_group_permission(userid, group_web_addr, False)
                    
    return render_to_response("ideas/ideaView.html",
                              {'ideas': ideas,'group':group, 'userid': userid, 'permission':permission},
                              context_instance = RequestContext(request))

# Helper function to obtain Group related to a group_web_address
def getGroupInfo(group_web_addr):
    return Group.objects.get(group_web_address= group_web_addr)